package homework.chattwo;

import sun.plugin2.main.server.HeartbeatThread;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class ChatSeverTwo {
    private ServerSocket serverSocket;
    private static final int PORT = 8888;
//    private List<PrintWriter> writerList=new ArrayList<>();
    private Map<String,PrintWriter> writerMap = new HashMap<>();
    private String host;
    private  Collection<PrintWriter> writerCollection;

    public ChatSeverTwo() {
        try {
            System.out.println("服务器启动...");
            serverSocket = new ServerSocket(PORT);
            System.out.println("服务器启动成功...");
        } catch (IOException e) {
            System.out.println("服务器启动失败...");
            e.printStackTrace();
            System.exit(-1);
        }
    }

    class ClientHandle implements Runnable {
        private Socket socket;



        public ClientHandle(Socket socket) {
            this.socket = socket;
            host = this.socket.getInetAddress().getHostAddress();
        }

        @Override
        public void run() {
            try {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(
                                socket.getInputStream(), StandardCharsets.UTF_8));

                PrintWriter pw = new PrintWriter(
                        new BufferedWriter(
                                new OutputStreamWriter(socket.getOutputStream(),
                                        StandardCharsets.UTF_8)),true);

                String userName =  br.readLine();
                writerMap.put(userName,pw);
                ServerToAllClient(userName+"上线啦...");

                String data;
                while ((data = br.readLine()) != null) {
                    if (data.startsWith("@")){
                        ServerToOneClient(data);
                    }else {
                       ServerToAllClient(data);
                    }
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                try {
                    System.out.println("客户端:" + socket + "退出...");
                    for(PrintWriter pws:writerCollection) {
                        pws.println("客户端:" + socket + "退出...");
                    }
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }


        }
    }

    private void ServerToAllClient(String data){
        System.out.println(host+"说:"+data);

        writerCollection = writerMap.values();
        for (PrintWriter printWriter : writerCollection){
            printWriter.println(host+"说:"+data);
        }

    }

    private void ServerToOneClient(String data){
        String msg = data.substring(data.lastIndexOf(":"));

        String name = data.substring(1,data.lastIndexOf(":"));

        if (writerMap.containsKey(name)){
            writerMap.get(name).println(host+"说"+msg);
        }else {
            ServerToAllClient(name+"下线了...");
        }


    }


    public void start() {

        Socket socket = null;
        try {
            while (true) {
                socket = serverSocket.accept();
                System.out.println("客户端:" + socket + "连接成功...");
                new Thread(new ClientHandle(socket)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new ChatSeverTwo().start();
    }

}
